package com.xilihui.xlh.business.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.xilihui.xlh.R;
import com.xilihui.xlh.business.entities.LoginEntity;
import com.xilihui.xlh.business.requests.LoginRequest;
import com.xilihui.xlh.constant.StrConst;
import com.xilihui.xlh.core.app.BaseApplication;
import com.xilihui.xlh.core.app.BaseCompatActivity;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.CountDown;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.TextExtend;
import com.xilihui.xlh.core.util.TextStringUtils;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import org.feezu.liuli.timeselector.Utils.TextUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/6/21.
 */

public class SmsLoginActivity extends BaseCompatActivity implements View.OnClickListener {
    
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.tv_sendCode)
    TextView tv_sendCode;
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.tv_xieyi)
    TextView tv_xieyi;
    
    private CountDown countDown;
    private long time = 0L;
    private String phone = "";
    private String code = "";
    
    @OnClick(R.id.iv_close)
    public void close(){
        finish();
    }
    
    @Override
    public int getLayout() {
        return R.layout.activity_sms_login;
    }

    @Override
    public String initTitle() {
        return null;
    }

    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {
        String str = "验证即登录，未注册自动创建账号并同意";
        String str2 = "《软件使用许可协议》";
        TextStringUtils.setSpanTextView(tv_xieyi,str+str2,new TextStringUtils.SpanColorHolder(
                0,str.length(),getResources().getColor(R.color.tv_666666)
        ));
        tv_sendCode.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        initcountDown();

        phone = (String) SPUtil.get(SmsLoginActivity.this,SPUtil.PHONE,"");
        et_phone.setText(phone);
        if(!TextUtil.isEmpty(phone)){
            et_phone.setSelection(phone.length());
        }
        
    }

    @Override
    public void initData() {
        
    }
    
    public void sendCode(){
        
        phone = et_phone.getText().toString().trim();
        code = et_code.getText().toString().trim();
        
        if(TextUtils.isEmpty(phone)){
            ToastUtil.toastShortNegative("请输入手机号码");
            return;
        }
        
        if(!TextExtend.isMobile(phone)){
            ToastUtil.toastShortNegative("请输入正确的手机号码");
            return;
        }

        tv_sendCode.setEnabled(false);
        
        LoginRequest.sendCode(phone, StrConst.scene_zc)
                .compose(DoTransform.<BaseEntity>applyLoading(this))
                .compose(SmsLoginActivity.this.<BaseEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<BaseEntity>(this) {
                    @Override
                    protected void onSuccess(BaseEntity entity) {
                        tv_sendCode.setEnabled(true);
                        ToastUtil.toastLongPositive(entity.getMsg());
                        countDown.execute(tv_sendCode, 60, new CountDown.Callback() {
                            @Override
                            public void onStart() {
                                tv_sendCode.setSelected(false);
                            }

                            @Override
                            public void onCounting(TextView tv, long second, String text) {
                                SPUtil.put(SmsLoginActivity.this,"time",System.currentTimeMillis()+second*1000);
                                LogUtil.i("mylog","set time:"+System.currentTimeMillis());
                            }

                            @Override
                            public void onFinish() {
                                tv_sendCode.setSelected(true);
                            }
                        });
                    }

                    @Override
                    protected void onFail(String msg) {
                        tv_sendCode.setEnabled(true);
                        ToastUtil.toastShortNegative(msg);
                    }
                });
        
    }
    
    public void regLogin(){

        phone = et_phone.getText().toString().trim();
        code = et_code.getText().toString().trim();

        if(TextUtils.isEmpty(phone)){
            ToastUtil.toastShortNegative("请输入手机号码");
            return;
        }

        if(!TextExtend.isMobile(phone)){
            ToastUtil.toastShortNegative("请输入正确的手机号码");
            return;
        }
        
        if(TextUtils.isEmpty(code)){
            ToastUtil.toastShortNegative("请输入验证码");
            return;
        }
        
        LoginRequest.smsLogin(SmsLoginActivity.this,phone,code)
                .compose(DoTransform.<LoginEntity>applyLoading(this))
                .compose(SmsLoginActivity.this.<LoginEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<LoginEntity>(this) {
                    @Override
                    protected void onSuccess(LoginEntity entity) {
                        ToastUtil.toastLongPositive(entity.getMsg());
                        SPUtil.put(SmsLoginActivity.this,SPUtil.TOKEN,entity.getAccess_token());
                        SPUtil.put(SmsLoginActivity.this,SPUtil.USER_ID,entity.getUser_id());
                        SPUtil.put(SmsLoginActivity.this,SPUtil.IS_LOGIN,true);

                        SPUtil.put(BaseApplication.get(),SPUtil.PHONE,phone);
                        
                        YEventBuses.post(new YEventBuses.Event("login_"));
                        Intent intent = new Intent(SmsLoginActivity.this,HomeActivity.class);
                        intent.putExtra("logout",2);
                        startActivity(intent);
                       
                        finish();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                    }
                });
        
    }

    public void initcountDown(){

        countDown = new CountDown();
        countDown.setTextOnCounting("", "重新发送");
        countDown.setTextOnFinished("发送验证码");
        countDown.setTv(tv_sendCode);

        time = (long) SPUtil.get(this,"time",0L);
        long curTime = System.currentTimeMillis();
        long residueTime = time-curTime;
        LogUtil.i("mylog","time:"+time+"\ncurTime:"+curTime+"\nresidueTime"+residueTime);
        long duration = residueTime/1000;
        LogUtil.i("mylog","duration:"+duration);
        if(duration>0){
            LogUtil.i("mylog","执行");
            countDown.execute((TextView) tv_sendCode, duration, new CountDown.Callback() {
                @Override
                public void onStart() {
                    tv_sendCode.setSelected(false);
                }

                @Override
                public void onCounting(TextView tv, long second, String text) {
                    SPUtil.put(SmsLoginActivity.this,"time",System.currentTimeMillis()+second*1000);
                    LogUtil.i("mylog","set time:"+System.currentTimeMillis());
                }

                @Override
                public void onFinish() {
                    tv_sendCode.setSelected(true);
                }
            });
        }
    }
    
    @OnClick(R.id.tv_accountLogin)
    public void toAccountLogin(){
        startActivity(new Intent(SmsLoginActivity.this,LoginActivity.class));
        finish();
    }
    
    @OnClick(R.id.tv_xieyi)
    public void xieyi(){
        Intent intent = new Intent(SmsLoginActivity.this,WebActivity.class);
        intent.putExtra("type",1);
        startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_sendCode:
                sendCode();
                break;
            case R.id.tv_login:
                regLogin();
                break;
        }
    }
    
    
}
